<?php


namespace app\cms\home\api;


use app\cms\dto\formContent;
use iflow\Response;
use iflow\Router\Controller;
use iflow\Router\implement\Request\PostMapping;
use think\facade\Db;

#[Controller('cms/home/api')]
class form {

    /**
     * 前端编辑表单内容
     * @param formContent $formContent
     * @return Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    #[PostMapping]
    public function addFormContent(formContent $formContent): Response
    {
        // code ...
        $info = $formContent -> getFormContent(true);
        if ($info instanceof Response) return $info;

        $formContent -> content['create_by'] = session('userInfo')['user_id'] ?? 0;
        $id = Db::name($info -> getForm()['form_name']) -> insertGetId($info -> create());

        if ($id) {
            $data['id'] = $id;
            return message() -> success('数据新建成功', $data);
        }
        return message() -> update_failed('数据新建失败');
    }

    /**
     * 更新表单数据
     * @param formContent $formContent
     * @return Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    #[PostMapping]
    public function updateFormContent(formContent $formContent): Response
    {
        $info = $formContent -> getFormContent(true);
        if ($info instanceof Response) return $info;
        if (
            Db::name($info -> getForm()['form_name']) -> where([
                'id' => $formContent -> content['id']
            ]) -> update($info -> getData())
        ) {
            return message() -> success('数据更新成功', $info -> content);
        }
        return message() -> update_failed('数据更新失败');
    }

}